package ae.pcfc.cldos.online.common.manager.provider;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.InitializingBean;

import ae.pcfc.cldos.online.common.manager.EncryptionManager;

/**
 * Encryption Service
 * 
 * @author arosa
 * 
 */
public class EncryptionManagerImpl implements EncryptionManager,
		InitializingBean {

	private static final String DEFAULT_PRIVATE_KEY = "0123456789123456";

	private String privateKey = DEFAULT_PRIVATE_KEY;
	
	
	public void setPrivateKey(String privateKey) {
		this.privateKey = privateKey;
	}

	private byte[] key = privateKey.getBytes();

	/**
	 * This method check properties
	 * 
	 * @throws Exception
	 */
	public void afterPropertiesSet() throws Exception {
		key = privateKey.getBytes();
		Integer keyLength = key.length;
		Double logValue = Math.log(keyLength) / Math.log(2.0);
		Double delta = Math.abs(logValue - Math.round(logValue));
		if (keyLength < 16 || delta.compareTo(0.01) > 0) {
			throw new IllegalArgumentException(
					"KEY MUST BE DEGREE OF TWO AND HIS LENGTH SHOUD BE MORE 16 BYTES");
		}
		
	}
	
	/**
	 * 
	 * Initialization of encryption and decryption objects
	 */
	public Cipher getCipher(int mode) {

		Cipher cipher = null;
		
		byte[] iv = new byte[] { 0x01, 0x07, 0x02, 0x04, 0x04, 0x05, 0x01,
				0x02, 0x08, 0x09, 0x0f, 0x0f, 0x0a, 0x01, 0x00, 0x0f };

		AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);

		try {
			cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		} catch (NoSuchAlgorithmException e) {
			System.err
					.println("ERROR WHEN CREATING ENCRYPTION SERVICE. NO SUCH ALGORITM");
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			System.err
					.println("ERROR WHEN CREATING ENCRYPTION SERVICE. NO SUCH PADDING");
			e.printStackTrace();
		}

		SecretKey secretKey = new SecretKeySpec(key, "AES");

		try {
			cipher.init(mode, secretKey, paramSpec);
		} catch (InvalidKeyException e) {
			System.err
					.println("ERROR WHEN CREATING ENCRYPTION SERVICE. BAD KEY!!");
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			System.err
					.println("ERROR WHEN CREATING ENCRYPTION SERVICE. BAD ALGHORITM INIT PARAMETER!!");
			e.printStackTrace();
		}
		return cipher;

	}

	public String encrypt(String in) {
		String encResult = "";
		Base64 base64UrlSafe = new Base64(76, new byte[]{}, true);
		byte[] input = null;
		input = in.getBytes();
		byte[] cipherText = null;

		try {
			cipherText = getCipher(Cipher.ENCRYPT_MODE).doFinal(input);
		} catch (IllegalBlockSizeException e) {
			System.err
					.println("ERROR WHEN ENCRYPTION MESSAGE! ILLEGAL BLOCK SIZE!");
			e.printStackTrace();
		} catch (BadPaddingException e) {
			System.err.println("ERROR WHEN ENCRYPTION MESSAGE! BAD PADDING!");
			e.printStackTrace();
		}

		encResult = base64UrlSafe.encodeToString(cipherText);
		return encResult;
	}

	public String decrypt(String in) {

		String decrResult = "";

		Base64 base64UrlSafe = new Base64(76, new byte[]{}, true);
		
		byte[] plainText = null;

		try {
			byte[] input = base64UrlSafe.decode(in);

			plainText = getCipher(Cipher.DECRYPT_MODE).doFinal(input);
		} catch (IllegalBlockSizeException e) {
			System.err
					.println("ERROR WHEN DECRYPTION MESSAGE! ILLEGAL BLOCK SIZE!");
			e.printStackTrace();
		} catch (BadPaddingException e) {
			System.err.println("ERROR WHEN DECRYPTION MESSAGE! BAD PADDING!");
			e.printStackTrace();
		} 

		if (plainText == null) {
			decrResult = "";
		} else {
			decrResult = new String(plainText);
		}

		return decrResult;
	}

	public String encode(String in) {

		String encoded = "";

		try {
			encoded = URLEncoder.encode(in, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			System.err.println("ERROR WHEN URL ENCODING");
			e.printStackTrace();
		}

		return encoded;

	}

	public String decode(String in) {

		String decoded = "";

		try {
			decoded = URLDecoder.decode(in, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			System.err.println("ERROR WHEN URL DECODING");
			e.printStackTrace();
		}

		return decoded;
	}

	public String encryptAndEncode(String in) {
		return encode(encrypt(in));
	}

	public String decodeAndDecrypt(String in) {
		return decrypt(decode(in));
	}
	
	public byte[] base64decodeToByteArray(String in){
		Base64 base64Base = new Base64();
		return base64Base.decode(in);
	}
	
	public String base64encodeToString(byte[] in){
		Base64 base64Base = new Base64();
		return base64Base.encodeToString(in);
	}
	
	public String base64decode(String in){
		Base64 base64Base = new Base64();
		return new String(base64Base.decode(in));
	}
}
